package org.example.dev.service.Impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.example.dev.service.ISDService;
import org.springframework.stereotype.Service;

import java.io.IOException;
@Service
@RequiredArgsConstructor
public class SDServiceImpl implements ISDService {

    private static final String TOKEN = "7tPFTSO8oSfu3V2k"; // 提供的token
    private static final OkHttpClient client = new OkHttpClient();


    @Override
    public String textToImage(String textDescription) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        String json = "{\"description\":\"" + textDescription + "\"}";
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url("https://www.szu-rjgc-xy.cn:8989/sd1")
                .post(body)
                .addHeader("Authorization", "Bearer " + TOKEN)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 解析响应体中的imageUrl
            String responseBody = response.body().string();
            // 假设响应体是JSON格式，包含imageUrl字段
            // 这里需要根据实际返回的JSON格式来解析
            // 示例解析逻辑，假设返回格式为 {"imageUrl": "http://example.com/image.jpg"}
            String imageUrl = responseBody.split("\"imageUrl\":\"")[1].split("\"")[0];
            return imageUrl;
        }
    }

    @Override
    public String imageToImage(String imageUrl) throws IOException {
        // 先调用图生文方法
        String textDescription = imageToText(imageUrl);
        // 再调用文生图方法
        return textToImage(textDescription);
    }

    private String imageToText(String imageUrl) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        String json = "{\"imageUrl\":\"" + imageUrl + "\"}";
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url("https://www.szu-rjgc-xy.cn:8989/sd2")
                .post(body)
                .addHeader("Authorization", "Bearer " + TOKEN)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 解析响应体中的description
            String responseBody = response.body().string();
            // 假设响应体是JSON格式，包含description字段
            // 这里需要根据实际返回的JSON格式来解析
            // 示例解析逻辑，假设返回格式为 {"description": "描述文字"}
            String description = responseBody.split("\"description\":\"")[1].split("\"")[0];
            return description;
        }
    }
}
